package com.juyu.miliao.api.service;

import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.LineTimeRedisDao;
import com.juyu.miliao.api.dao.redis.MakeFriendsRedisDao;
import com.juyu.miliao.api.dao.redis.UserCallRedisDao;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.common.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class LineTimeService {
    private final Logger logger = LoggerFactory.getLogger("lineTimeRabbitMQ");
    @Resource
    private LineTimeRedisDao lineTimeRedisDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserCallRedisDao userCallRedisDao;
    @Resource
    private MakeFriendsRedisDao makeFriendsRedisDao;
    @Resource
    private EnergyLevelService energyLevelService;
    @Resource
    private UserWalletDao userWalletDao;

    /**
     * 统计用户在线时长
     *
     * @param eventType 值为2，表示是登录事件的消息
     *                  值为3，表示是登出事件的消息
     * @param accid     用户帐号
     * @param timestamp 时间戳
     */
//    @Transactional(rollbackFor = Exception.class)
    public void countLineTime(String eventType, String accid, String timestamp,User user) {
        Optional<User> optUser = Optional.ofNullable(user);
        //登录事件
        if (Integer.parseInt(eventType) == 2) {
            //过滤用户在繁忙状态存入在线列表
            if (user.getIsVideo() != 2) {
                //判断accid是否存在，如果存在则先删除redis中的值，重新计算
                if (optUser.isPresent()) {
                    logger.info("登录事件：保存accid = {}", accid);
                    if (user.getEnable() == 2) {
                        logger.info("账号被封禁-事件：{},accid:{}", eventType, accid);
                        return;
                    }
                    Boolean temp = lineTimeRedisDao.hasKeyLine(accid);
                    if (!temp) {
                        lineTimeRedisDao.addLine(accid, timestamp);
                    } else {
                        lineTimeRedisDao.deleteLine(accid);
                        lineTimeRedisDao.addLine(accid, timestamp);
                    }
                    /** 03-13粉包需求：判断用户是否是mmjy包登录*/
//                    logger.info("粉包需求：" + accid + "，结果：" + lineTimeRedisDao.isMemberUserLoginPackageId(accid, "mmjy"));
//                    if (lineTimeRedisDao.isMemberUserLoginPackageId(accid, "mmjy")) {
//                        logger.info("粉包需求：" + accid + "存储redis");
//                        lineTimeRedisDao.addOnLineByAppPackageIdBySex(user.getSex(), accid, "mmjy");
//                    }
//                    logger.info("花蜜需求：" + accid + "，结果：" + lineTimeRedisDao.isMemberUserLoginPackageId(accid, "huami"));
//                    if (lineTimeRedisDao.isMemberUserLoginPackageId(accid, "huami")) {
//                        logger.info("花蜜需求：" + accid + "存储redis");
//                        lineTimeRedisDao.addOnLineByAppPackageIdBySex(user.getSex(), accid, "huami");
//                    }
                    if (user.getIsHost() == 1 && user.getIsRobot()==2) {
                        lineTimeRedisDao.addHostLine(accid);
                        lineTimeRedisDao.addHostLineBySex(user.getSex(), accid);
                        //删除繁忙
                        userCallRedisDao.endHostCall(CommonUtil.null2Int(accid));
                        //1.5.3 是否是新人主播
                        if (lineTimeRedisDao.isMemberThirtyDaysNewHost(accid)) {
                            lineTimeRedisDao.addOnLineThirtyDaysNewHost(accid);
                            lineTimeRedisDao.removeHostUserSingOutDateTimeByNew(accid);
                        }
                        lineTimeRedisDao.removeHostUserSingOutDateTimeByHost(accid);
                    } else {
                        lineTimeRedisDao.addCommonUser(accid, user.getvGradeSum());
                        //根据性别存放普通在线用户，根据v/m值排序
                        int sort = 0;
                        if (user.getSex() == 1) {
                            sort = user.getvGradeSum();
                        } else if (user.getSex() == 2) {
                            sort = user.getmGradeSum();
                        }
                        lineTimeRedisDao.addOnLineUserBySex(user.getSex(), accid, sort);
                        //1.5.2 三天内注册用户
                        if (lineTimeRedisDao.isMemberThreeDaysNewUser(accid)) {
                            lineTimeRedisDao.addOnLineThreeDaysNewUser(accid);
                        }
                        UserWallet userWallet = userWalletDao.getUserWalletById(Long.parseLong(accid));
                        logger.info("壕友列表增加,userId::"+accid+",rechargeAmount::"+userWallet.getRechargeAmount());
                        if (userWallet.getRechargeAmount() > 0) {
                            Boolean b = lineTimeRedisDao.addOnlineRechargeAmountUser(accid);
                            logger.info("壕友列表增加,userId::"+accid+",boolean::"+b);
                        }
                    }
                    /**添加在线同城缓存*/
                    logger.info("添加在线同城缓存:" + user.getUserId() + ",province=" + user.getLocationProvince() +
                            "|city=" + user.getLocationCity());
                    makeFriendsRedisDao.updateLocation(user, null, 1);
                } else {
                    logger.info("LineTimeService-countLineTime：accid错误同步={}", accid);
                }
            }

        } else if (Integer.parseInt(eventType) == 3) {
            if (optUser.isPresent()) {
                countLineTimeEnergyLevel(user, timestamp);
            }
            //登出事件
            logger.info("登出事件：保存accid = {}", accid);
//            if (lineTimeRedisDao.hasKeyLine(accid)) {
            lineTimeRedisDao.deleteLine(accid);
            lineTimeRedisDao.deleteCommonUser(accid);
            /** 03-13粉包需求：判断用户是否是mmjy包登录*/
            lineTimeRedisDao.removeOnLineByAppPackageIdBySex(1, accid, "mmjy");
            lineTimeRedisDao.removeOnLineByAppPackageIdBySex(2, accid, "mmjy");
            lineTimeRedisDao.removeOnLineByAppPackageIdBySex(1, accid, "huami");
            lineTimeRedisDao.removeOnLineByAppPackageIdBySex(2, accid, "huami");
            //1.5.6 首页列表维护主播登出时间
            if(user.getIsHost()==1 && user.getIsRobot()==2 && user.getEnable()!=2){
                if(lineTimeRedisDao.isMemberThirtyDaysNewHost(accid)){
                    lineTimeRedisDao.setHostUserSingOutDateTimeByNew(accid);
                }
                lineTimeRedisDao.setHostUserSingOutDateTimeByHost(accid);
            }
            if(user.getIsHost()==1 && (user.getEnable()==2 || user.getIsRobot()==1)){
                lineTimeRedisDao.removeHostUserSingOutDateTimeByNew(accid);
                lineTimeRedisDao.removeHostUserSingOutDateTimeByHost(accid);
            }
            lineTimeRedisDao.removeOnLineThreeDaysNewUser(accid);
            //新人主播
            lineTimeRedisDao.removeOnLineThirtyDaysNewHost(accid);
            lineTimeRedisDao.removeOnlineRechargeAmountUser(accid);
            if (optUser.isPresent()) {
                //操作主播登出
                lineTimeRedisDao.deleteHostLine(accid);
                lineTimeRedisDao.deleteHostLineBySex(1, accid);
                lineTimeRedisDao.deleteHostLineBySex(2, accid);
                //删除繁忙
                userCallRedisDao.endHostCall(CommonUtil.null2Int(accid));
                //删除在线列表
                lineTimeRedisDao.deleteOnLineUserBySex(1, accid);
                lineTimeRedisDao.deleteOnLineUserBySex(2, accid);
            }

            //删除在线同城缓存
//                logger.info("删除在线同城缓存:"+user.getUserId()+",province="+user.getLocationProvince()+
//                        "|city="+user.getLocationCity());
            if (user != null) {
                makeFriendsRedisDao.deleteMakeFriendsCache(user);
            }

//            }
        }
    }


    private void countLineTimeEnergyLevel(User user, String endTimestamp) {
        try {
            String startTimestamp = lineTimeRedisDao.findLine(user.getUserId() + "");
            if (startTimestamp == null || startTimestamp.equals("null") || startTimestamp.equals(""))
                return;
            Long temp = Long.parseLong(endTimestamp) - Long.parseLong(startTimestamp);
            temp = temp / 1000 / 60 / 3;
            if (temp > 0) {
                energyLevelService.addUserEnergyLevel(user.getUserId(), EnergyLevelType.ENERGY_TYPE_ONLINE, temp.intValue());
            }
        } catch (RuntimeException e) {
            logger.info("计算能量值异常：" + e);
        }

    }
}
